package com.example.widget_lib.widget.progress.circle;

import com.example.widget_lib.utils.AttrUtils;
import com.example.widget_lib.utils.PxUtil;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.render.*;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.agp.utils.RectFloat;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

/**
 * 自定义view实现环形带刻度颜色渐变的进度条
 */
public class CircleProgress extends Component implements Component.DrawTask {

    private static final String TAG = "CircleProgress";

    private Context mContext;
    // 默认大小
    private int mDefaultSize;
    // 是否开启抗锯齿
    private boolean antiAlias;
    // 绘制提示
    private Paint mHintPaint;
    private CharSequence mHint;
    private int mHintColor;
    private float mHintSize;
    private float mHintOffset;

    // 绘制单位
    private Paint mUnitPaint;
    private CharSequence mUnit;
    private int mUnitColor;
    private float mUnitSize;
    private float mUnitOffset;

    // 绘制数值
    private Paint mValuePaint;
    private float mValue;
    private float mMaxValue;
    private float mValueOffset;
    private int mPrecision;
    private String mPrecisionFormat;
    private int mValueColor;
    private float mValueSize;

    // 绘制圆弧
    private Paint mArcPaint;
    private float mArcWidth;
    private float mStartAngle, mSweepAngle;
    private RectFloat mRectF;
    // 当前进度，[0.0f,1.0f]
    private float mPercent;
    // 初始的进度
    private float originPercent;
    // 动画时间
    private long mAnimTime = 1000;
    private AnimatorValue mAnimator;

    // 绘制背景圆弧
    private Paint mBgArcPaint;
    private int mBgArcColor;
    private int mArcColor;
    private float mBgArcWidth;

    // 圆心坐标，半径
    private Point mCenterPoint;
    private float mRadius;
    private float mTextOffsetPercentInRadius;

    private int mArcCenterX;
    // 内部虚线的外部半径
    private float mExternalDottedLineRadius;
    // 内部虚线的内部半径
    private float mInsideDottedLineRadius;

    // 线条数
    private int mDottedLineCount = 100;
    // 圆弧跟虚线之间的距离
    private int mLineDistance = 20;
    // 线条宽度
    private int mDottedLineWidth = 12;
    // 是否使用渐变
    private boolean useGradient = true;
    // 前景色起始颜色
    private int mForeStartColor;
    // 前景色结束颜色
    private int mForeEndColor;

    public CircleProgress(Context context, AttrSet attrSet) {
        super(context, attrSet);
        init(context, attrSet);
        setBindStateChangedListener(new BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {

            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                // 释放资源
                mAnimator.cancel();
                mAnimator = null;
            }
        });
        addDrawTask(this);
    }

    @Override
    public void addDrawTask(DrawTask task) {
        super.addDrawTask(task);
        task.onDraw(this, mCanvasForTaskOverContent);
    }

    private void init(Context context, AttrSet attrSet) {
        mContext = context;
        mDefaultSize = (int) PxUtil.vp2px(150);
        mRectF = new RectFloat();
        mCenterPoint = new Point();
        initAttrs(attrSet);
        initPaint();
        setValue(mValue);
    }

    private void initAttrs(AttrSet attrSet) {
        antiAlias = AttrUtils.getBooleanFromAttr(attrSet, "antiAlias", true);
        mHint = AttrUtils.getStringFromAttr(attrSet, "hint", "");
        mHintColor = AttrUtils.getColorFromAttr(attrSet, "hintColor", Color.BLACK.getValue());
        mHintSize = AttrUtils.getDimensionFromAttr(attrSet, "hintSize", 15);
        mValue = AttrUtils.getIntegerFromAttr(attrSet, "value", 50);
        mMaxValue = AttrUtils.getIntegerFromAttr(attrSet, "maxValue", 50);
        // 内容数值精度格式
        mPrecision = AttrUtils.getIntegerFromAttr(attrSet, "precision", 0);
        mPrecisionFormat = getPrecisionFormat(mPrecision);
        mValueSize = AttrUtils.getDimensionFromAttr(attrSet, "valueSize", 15);
        mValueColor = AttrUtils.getColorFromAttr(attrSet, "valueColor", Color.BLACK.getValue());
        mUnit = AttrUtils.getStringFromAttr(attrSet, "unit", "");
        mUnitColor = AttrUtils.getColorFromAttr(attrSet, "unitColor", Color.BLACK.getValue());
        mUnitSize = AttrUtils.getDimensionFromAttr(attrSet, "unitSize", 30);
        mArcWidth = AttrUtils.getDimensionFromAttr(attrSet, "arcWidth", 15);
        mStartAngle = AttrUtils.getIntegerFromAttr(attrSet, "startAngle", 270);
        mSweepAngle = AttrUtils.getIntegerFromAttr(attrSet, "sweepAngle", 360);

        mBgArcColor = AttrUtils.getColorFromAttr(attrSet, "bgArcColor", Color.WHITE.getValue());
        mArcColor = AttrUtils.getColorFromAttr(attrSet, "arcColors", Color.RED.getValue());
        mBgArcWidth = AttrUtils.getDimensionFromAttr(attrSet, "bgArcWidth", 15);
        mTextOffsetPercentInRadius = AttrUtils.getFloatFromAttr(attrSet, "textOffsetPercentInRadius", 0.33f);
        mAnimTime = AttrUtils.getIntegerFromAttr(attrSet, "animTime", 1000);
        mDottedLineCount = AttrUtils.getIntegerFromAttr(attrSet, "dottedLineCount", mDottedLineCount);
        mLineDistance = AttrUtils.getIntegerFromAttr(attrSet, "lineDistance", mLineDistance);
        mDottedLineWidth = AttrUtils.getDimensionFromAttr(attrSet, "dottedLineWidth", mDottedLineWidth);
        mForeStartColor = AttrUtils.getColorFromAttr(attrSet, "foreStartColor", Color.BLUE.getValue());
        mForeEndColor = AttrUtils.getColorFromAttr(attrSet, "foreEndColor", Color.BLUE.getValue());
    }

    private void initPaint() {
        mHintPaint = new Paint();
        // 设置抗锯齿，会消耗较大资源，绘制图形速度会变慢
        mHintPaint.setAntiAlias(antiAlias);
        // 设置绘制文字大小
        mHintPaint.setTextSize((int) mHintSize);
        // 设置画笔颜色
        mHintPaint.setColor(new Color(mHintColor));
        // 从中间向两边绘制，不需要再次计算文字
        mHintPaint.setTextAlign(TextAlignment.CENTER);

        mValuePaint = new Paint();
        mValuePaint.setAntiAlias(antiAlias);
        mValuePaint.setTextSize((int) mValueSize);
        mValuePaint.setColor(new Color(mValueColor));
        // 设置TypeFace对象，即字体风格，包括粗体，斜体以及衬线体，非衬线体等
        mValuePaint.setFont(Font.DEFAULT_BOLD);
        mValuePaint.setTextAlign(TextAlignment.CENTER);

        mUnitPaint = new Paint();
        mUnitPaint.setAntiAlias(antiAlias);
        mUnitPaint.setTextSize((int) mUnitSize);
        mUnitPaint.setColor(new Color(mUnitColor));
        mUnitPaint.setTextAlign(TextAlignment.CENTER);

        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(antiAlias);
        // 设置画笔的样式，为FILL，FILL_OR_STROKE，或STROKE
        mArcPaint.setStyle(Paint.Style.STROKE_STYLE);
        // 设置画笔粗细
        mArcPaint.setStrokeWidth(mArcWidth);
        // 当画笔样式为STROKE或FILL_OR_STROKE时，设置笔刷的图形样式，如圆形样式 Cap.ROUND(圆形样式)或Cap.SQUARE(方形样式)
        mArcPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);

        mBgArcPaint = new Paint();
        mBgArcPaint.setAntiAlias(antiAlias);
        mBgArcPaint.setColor(new Color(mBgArcColor));
        mBgArcPaint.setStyle(Paint.Style.STROKE_STYLE);
        mBgArcPaint.setStrokeWidth(mBgArcWidth);
        mBgArcPaint.setStrokeCap(Paint.StrokeCap.ROUND_CAP);
    }

    private float getBaselineOffsetFromY(Paint paint) {
        Paint.FontMetrics fontMetrics = paint.getFontMetrics();
        return ((Math.abs(fontMetrics.ascent) - fontMetrics.descent)) / 2;
    }

    private void onSizeChanged() {
        mArcCenterX = (int) (getWidth() / 2.f);
        // 求圆弧和背景圆弧的最大宽度
        float maxArcWidth = Math.max(mArcWidth, mBgArcWidth);
        // 求最小值作为实际值
        int minSize = Math.min(getWidth() - getPaddingLeft() - getPaddingRight() - 2 * (int) maxArcWidth,
                getHeight() - getPaddingTop() - getPaddingBottom() - 2 * (int) maxArcWidth);
        // 减去圆弧的宽度，否则会造成部分圆弧绘制在外围
        mRadius = minSize / 2;
        // 获取圆的相关参数
        mCenterPoint.modify(getWidth() / 2, getHeight() / 2);
        // 绘制圆弧的边界
        mRectF.left = mCenterPoint.getPointX() - mRadius - maxArcWidth / 2;
        mRectF.top = mCenterPoint.getPointY() - mRadius - maxArcWidth / 2;
        mRectF.right = mCenterPoint.getPointX() + mRadius + maxArcWidth / 2;
        mRectF.bottom = mCenterPoint.getPointY() + mRadius + maxArcWidth / 2;
        // 计算文字绘制时的 baseline,
        // 由于文字的baseline、descent、ascent等属性只与textSize和typeface有关，所以此时可以直接计算,
        // 若value、hint、unit由同一个画笔绘制或者需要动态设置文字的大小，则需要在每次更新后再次计算
        mValueOffset = mCenterPoint.getPointY() + getBaselineOffsetFromY(mValuePaint);
        mHintOffset = mCenterPoint.getPointY() - mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mHintPaint);
        mUnitOffset = mCenterPoint.getPointY() + mRadius * mTextOffsetPercentInRadius + getBaselineOffsetFromY(mUnitPaint);

        if (useGradient) {
            Point[] points = new Point[]{new Point(0, 0), new Point(getWidth(), getHeight())};
            Color[] colors = new Color[]{new Color(mForeEndColor), new Color(mForeStartColor)};
            LinearShader shader = new LinearShader(points, null, colors, Shader.TileMode.CLAMP_TILEMODE);
            mArcPaint.setShader(shader, Paint.ShaderType.LINEAR_SHADER);
        } else {
            mArcPaint.setShader(null, Paint.ShaderType.LINEAR_SHADER);
            mArcPaint.setColor(new Color(mArcColor));
        }

        // 虚线的外部半径
        mExternalDottedLineRadius = (int) (mRectF.getWidth() / 2) + mLineDistance;
        // 虚线的内部半径
        mInsideDottedLineRadius = mExternalDottedLineRadius - mDottedLineWidth;
    }

    @Override
    public void onDraw(Component component, Canvas canvas) {
        onSizeChanged();
        drawArc(canvas);
        drawText(canvas);
    }

    private void drawArc(Canvas canvas) {
        // 从进度圆弧结束的地方开始重新绘制，优化性能
        canvas.save();

        // 绘制背景圆弧
        // 360 * Math.PI / 180
        // 虚线分割点角度(2个度数一条线)
        float everyDegrees = (float) (2.0f * Math.PI / mDottedLineCount);
        // 起始角度在圆环上的坐标点
        float startDegrees = (float) (135 * Math.PI / 180);
        // 结束角度在圆环上的坐标点
        float endDegrees = (float) (225 * Math.PI / 180);
        for (int i = 0; i < mDottedLineCount; i++) {
            float degrees = i * everyDegrees;
            // 过滤底部90度的弧长
            if (degrees > startDegrees && degrees < endDegrees) {
                continue;
            }
            float startX = mArcCenterX + (float) Math.sin(degrees) * mInsideDottedLineRadius;
            float startY = mArcCenterX - (float) Math.cos(degrees) * mInsideDottedLineRadius;

            float stopX = mArcCenterX + (float) Math.sin(degrees) * mExternalDottedLineRadius;
            float stopY = mArcCenterX - (float) Math.cos(degrees) * mExternalDottedLineRadius;

            canvas.drawLine(new Point(startX, startY), new Point(stopX, stopY), mBgArcPaint);
        }

        canvas.rotate(mStartAngle, mCenterPoint.getPointX(), mCenterPoint.getPointY());

        // 第一个参数 oval 为 RectF 类型，即圆弧显示区域
        // startAngle 和 sweepAngle  均为 float 类型，分别表示圆弧起始角度和圆弧度数
        // 3点钟方向为0度，顺时针递增
        // 如果 startAngle < 0 或者 > 360,则相当于 startAngle % 360
        // useCenter:如果为True时，在绘制圆弧时将圆心包括在内，通常用来绘制扇形
        float currentAngle = mSweepAngle * mPercent;
        canvas.drawArc(mRectF, new Arc(2, currentAngle, false), mArcPaint);
        canvas.restore();
    }

    /**
     * 绘制内容文字
     *
     * @param canvas
     */
    private void drawText(Canvas canvas) {
        canvas.drawText(mValuePaint, String.format(mPrecisionFormat, mValue), mCenterPoint.getPointX(), mValueOffset);

        if (mHint != null) {
            canvas.drawText(mHintPaint, mHint.toString(), mCenterPoint.getPointX(), mHintOffset);
        }

        if (mUnit != null) {
            canvas.drawText(mUnitPaint, mUnit.toString(), mCenterPoint.getPointX(), mUnitOffset);
        }
    }

    public float getMaxValue() {
        return mMaxValue;
    }

    public void setMaxValue(float maxValue) {
        mMaxValue = maxValue;
    }

    public int getPrecision() {
        return mPrecision;
    }

    public void setPrecision(int precision) {
        mPrecision = precision;
        mPrecisionFormat = getPrecisionFormat(precision);
    }

    public long getAnimTime() {
        return mAnimTime;
    }

    public void setAnimTime(long animTime) {
        mAnimTime = animTime;
    }

    /**
     * 重置
     */
    public void reset() {
        startAnimator(mPercent, 0.0f, 1000L);
    }

    /**
     * 设置当前值
     *
     * @param value
     */

    public void setValue(float value) {
        if (value > mMaxValue) {
            value = mMaxValue;
        }
        float start = mPercent;
        float end = value / mMaxValue;
        originPercent = start;
        startAnimator(start, end, mAnimTime);
    }

    private void startAnimator(float start, float end, long animTime) {
        mAnimator = new AnimatorValue();
        mAnimator.setDuration(animTime);
        mAnimator.setValueUpdateListener((animatorValue, v) -> {
            mPercent = originPercent - (start - end) * v;
            mValue = mPercent * mMaxValue;
            invalidate();
        });
        mAnimator.start();
    }

    /**
     * 获取数值精度格式化字符串
     *
     * @param precision
     * @return  返回字符串
     */
    private String getPrecisionFormat(int precision) {
        return "%." + precision + "f";
    }
}
